var app = getApp()
var util = require('./util')

function search(that, suffix) {
  if (that.data.storeName !== '') {
    util.request('/sales/shop/search', {
      shop: that.data.storeName,
      suffix: suffix
    }, 'GET').then(res => {
      let searchlist = res.data;
      that.setData({
        searchlist
      })
    })
  } else {
    that.setData({
      searchlist: '',
    })
  }
}

function load(that, suffix) {
  var auth;
  var set = function () {
    wx.getLocation({
      success(res) {
        console.log(res)
        const lat = res.latitude
        const lon = res.longitude
        app.loadAction(async res=>{
          if (!app.globalData.loadAction) {
            util.request('/sales/shop', {
              lon: lon,
              lat: lat,
              suffix: suffix
            }, 'GET').then(res => {
              let data = res.data;
              console.log(res)
              that.setData({
                nearby: data
              })
            })
          }
        })
      },
      fail: function (res) {

      }
    })
  }
  wx.showLoading({
    title: '调取中',
  })
  wx.getSetting({
    success: function (res) {
      wx.hideLoading()
      auth = res.authSetting
      if (!auth['scope.userLocation']) {
        wx.showModal({
          title: '未允许获取位置信息，请确认是否已开启【位置信息】，允许获取位置信息。',
          success: function (res) {
            console.log(res)
            if (res.confirm) {
              wx.openSetting({
                withSubscriptions: true,
              })
              var val = setInterval(() => {
                wx.getSetting({
                  success: function (res) {
                    if (res.authSetting['scope.userLocation']) {
                      set()
                      clearInterval(val)
                    }
                  }
                })
              }, 1000);
            }
          }
        })
      } else {
        set()
      }
    }
  })

}

function choose(e, that) {
  var ind = e.currentTarget.dataset.index;
  var mold = e.currentTarget.dataset.mold;
  switch (mold) {
    case 'nearby':
      that.setData({
        shop: that.data.nearby[ind].shop
      })
      break;
    default:
      that.setData({
        shop: that.data.searchlist[ind].shop
      })
  }
}

function choose_or(e, that) {
  var ind = e.currentTarget.dataset.index;
  var mold = e.currentTarget.dataset.mold;
  switch (mold) {
    case 'nearby':
      wx.setStorageSync('shop_label', that.data.nearby[ind].shop)
      break;
    default:
      wx.setStorageSync('shop_label', that.data.searchlist[ind].shop)
  }
  wx.navigateBack({
    delta: 0,
  })
}

module.exports = {
  choose,
  choose_or,
  search,
  load
}